package ahblue.cn.tanzi.util;

import android.content.Context;
import android.content.SharedPreferences;
import android.text.TextUtils;
import android.util.Base64;


import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.io.StreamCorruptedException;
import java.util.List;
import java.util.Map;


/**
 * 2017/4/7 AM 9:25 max
 * 添加一个位置的信息的保存字段 Mylocation
 */
public class SharePreferenceUtil {

    private SharedPreferences sp;
    private SharedPreferences.Editor editor;


    public SharePreferenceUtil(Context context) {
        if (context != null){
            sp = context.getSharedPreferences("qiji_sharedpreferences", context.MODE_PRIVATE);
            editor = sp.edit();
        }
    }

    public void clearData() {
        editor.clear();
        editor.commit();
    }

    public void clearKey(String key){
        editor.remove(key);
        editor.commit();
    }

    /**
     * 用户的位置信息
     * Latitude
     */

    public void setLatitude(String Latitude) {
        editor.putString("Latitude",Latitude);
        editor.commit();

    }

    public String getLatitude() {
        return sp.getString("Latitude","");
    }
    public void setLongitude(String Longitude) {
        editor.putString("Longitude",Longitude);
        editor.commit();

    }

    public String getLongitude() {
        return sp.getString("Longitude","");
    }


    /**
     * 首页版本更新提示，是否忽略此版本更新
     */
    public void setIgnoreVersion(String ignoreVersion) {
        editor.putString("ignoreVersion", ignoreVersion);
        editor.commit();
    }

    public String getIgnoreVersion() {
        return sp.getString("ignoreVersion", "");
    }


    /**
     * 标识从哪里进入注册页面
     */

    public void setRegistFlag(int flag) {
        editor.putInt("registflag", flag);
        editor.commit();
    }

    public int getRegistFlag() {
        return sp.getInt("registflag", 0);
    }

    /**
     * 是否登陆
     */

    public void setIsLoginIn(boolean is) {
        editor.putBoolean("isLogin", is);
        editor.commit();

    }

    public boolean getIsLoginIn() {
        return sp.getBoolean("isLogin", false);
    }


    public void setOrderId(String orderId) {
        editor.putString("orderId", orderId);
        editor.commit();
    }

    public String getOrderId() {
        return sp.getString("orderId", "");
    }



    // 保存电话号码
    public void setPhoneNum(String phoneNum) {
        editor.putString("phoneNum", phoneNum);
        editor.commit();
    }

    // 获取电话号码
    public String getPhoneNum() {
        return sp.getString("phoneNum", "");
    }



    // 保存用户类型
    public void setUserType(String type) {
        editor.putString("type", type);
        editor.commit();
    }


    // 保存用户id
    public void setUserId(String userId) {
        editor.putString("userId", userId);
        editor.commit();
    }

    // 获取用户id
    public String getUserId() {
        return sp.getString("userId", "");
    }


    // 保存用户昵称
    public void setNickName(String nickName) {
        editor.putString("nickName", nickName);
        editor.commit();
    }

    // 获取用户昵称
    public String getNickName() {
        return sp.getString("nickName", "");
    }

    // 用户的密码
    public void setPasswd(String passwd) {
        editor.putString("passwd", passwd);
        editor.commit();
    }

    public String getPasswd() {
        return sp.getString("passwd", "");
    }


    // 用户性别 1为男 2为女
    public void setSex(String sex) {
        editor.putString("sex", sex);
        editor.commit();
    }



    public String getSex() {
        return sp.getString("sex", "");
    }
    public String getBirth() {
        return sp.getString("birth", "");
    }

    // 用户生日
    public void setBirth(String birth) {
        editor.putString("birth", birth);
        editor.commit();
    }

    // 用户访问令牌
    public void setToken(String token) {
        editor.putString("token", token);
        editor.commit();
    }

    public String getToken() {
        return sp.getString("token", "");
    }


    // 用户的id
    public void setId(String id) {
        editor.putString("id", id);
        editor.commit();
    }

    public String getId() {
        return sp.getString("id", "");
    }

    // 用户的昵称
    public String getName() {
        return sp.getString("name", "");
    }

    public void setName(String name) {
        editor.putString("name", name);
        editor.commit();
    }

    // 登录用户名
    public String getLoginName() {
        return sp.getString("loginName", "");
    }

    public void setLoginName(String loginName) {
        editor.putString("loginName", loginName);
        editor.commit();
    }

    // 是否第一次运行本应用
    public void setIsFirst(boolean isFirst) {
        editor.putBoolean("isFirst", isFirst);
        editor.commit();
    }

    public boolean getisFirst() {
        return sp.getBoolean("isFirst", true);
    }


    /**
     * 是否关闭位置搜索
     */
    public void setClose(boolean close) {
        editor.putBoolean("close", close);
        editor.commit();
    }

    /**
     * 获取缓存的
     *
     * @return
     */
    public boolean isClose() {
        return sp.getBoolean("close", true);
    }



    public void saveObject(Object ob, String key){
        // 创建字节输出流
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            // 创建对象输出流，并封装字节流
            ObjectOutputStream oos = new ObjectOutputStream(baos);
            // 将对象写入字节流
            oos.writeObject(ob);
            // 将字节流编码成base64的字符窜
            String oAuth_Base64 = new String(Base64.encode(baos
                    .toByteArray(),Base64.DEFAULT));
//            Base64.encode()

            editor.putString(key, oAuth_Base64);

            editor.commit();
            oos.close();
            baos.close();
        } catch (IOException e) {
            // TODO Auto-generated
        }
    }

    public Object getObject(String key) {
        Object ob = null;

        String productBase64 = sp.getString(key, "");

        //读取字节
        byte[] base64 = Base64.decode(productBase64.getBytes(),Base64.DEFAULT);

        //封装到字节流
        ByteArrayInputStream bais = new ByteArrayInputStream(base64);
        try {
            //再次封装
            ObjectInputStream bis = new ObjectInputStream(bais);
            try {
                //读取对象
                ob = bis.readObject();
                bis.close();
                bais.close();
            } catch (ClassNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        } catch (StreamCorruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return ob;
    }


    public void setDownloadId(long id){
        editor.putLong("downloadID",id);
        editor.commit();
    }
    public long getDownloadId(){
        long res =sp.getLong("downloadID",-1);
        return res;
    }

    /**
     * 购物车是否有商品
     */

    public void setHasShopCart(boolean flag) {
        editor.putBoolean("ShopCart", flag);
        editor.commit();

    }

    public boolean isHasShopCart() {
        return sp.getBoolean("ShopCart", false);
    }


    /**
     *
     */

    public void setUnReadMsg(boolean flag) {
        editor.putBoolean("UnReadMsg", flag);
        editor.commit();

    }

    public boolean isUnReadMsg() {
        return sp.getBoolean("UnReadMsg", false);
    }

    /**
     *
     */

    public void setLocation(String flag) {
        editor.putString("Location", flag);
        editor.commit();

    }

    public String getLocation() {
        return sp.getString("Location",null);
    }

    /**
     * 是否弹出通知栏权限被禁止提示
     */
    public Boolean isPopupNotification(){
        return sp.getBoolean("isPopupNotification",true);
    }

    public void setIsPopupNotification(Boolean isPopupNotification){
        editor.putBoolean("isPopupNotification",isPopupNotification);
        editor.commit();
    }

    /**
     * 是否已更新XGToken
     */
    public Boolean isUpdatedXGToken(){
        return sp.getBoolean("isUpdatedXGToken",false);
    }

    public void setIsUpdatedXGToken(Boolean isUpdatedXGToken){
        editor.putBoolean("isUpdatedXGToken",isUpdatedXGToken);
        editor.commit();
    }

    /**
     * 获取上一次请求检测是否有新补丁的时间戳
     * @return
     */
    public Long getLastQueryAndLoadNewPatchTime(){
        return sp.getLong("lastQueryAndLoadNewPatchTime",0L);
    }

    public void setLastQueryAndLoadNewPatchTime(Long time){
        editor.putLong("lastQueryAndLoadNewPatchTime",time);
        editor.commit();
    }


    /**
     * 是否需要结束当前app的进程，在有新补丁加载后需要重启app时需要结束进程
     * @return
     */
    public boolean isKillProcess(){
        return sp.getBoolean("isKillProcess",false);
    }

    public void setIsKillProcess(boolean isKillProcess){
        editor.putBoolean("isKillProcess",isKillProcess);
        editor.commit();
    }

    /**
     * 是否是第一次打开收货地址定位
     * @return
     */
    public boolean isFirstOpenMapLocation(){
        return sp.getBoolean("isFirstOpenMapLocation",true);
    }

    public void setIsFirstOpenMapLocation(boolean isFirstOpenMapLocation){
        editor.putBoolean("isFirstOpenMapLocation",isFirstOpenMapLocation);
        editor.commit();
    }



    /**
     * 购物车中商品的数量
     * @return
     */
    public int getShoppingCardCount(){
        return sp.getInt("shoppingCardCount",0);
    }

    public void setShoppingCardCount(int shoppingCardCount){
        editor.putInt("shoppingCardCount",shoppingCardCount);
        editor.commit();
    }

    /**
     * 存储Map集合
     * @param context 上下文
     * @param key 键
     * @param map 存储的集合
     * @param <K> 指定Map的键
     * @param <V> 指定Map的值
     */
    public <K extends Serializable, V extends Serializable> void putMap(Context context, String key, Map<K, V> map){
        try {
            put(context, key, map);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public <K extends Serializable, V extends Serializable> Map<K, V> getMap(Context context, String key){
        try {
            return (Map<K, V>) get(context, key);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**存储对象*/
    private void put(Context context, String key, Object obj)throws IOException {
        if (obj == null) {//判断对象是否为空
            return;
        }
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream oos  = null;
        oos = new ObjectOutputStream(baos);
        oos.writeObject(obj);
        // 将对象放到OutputStream中
        // 将对象转换成byte数组，并将其进行base64编码
        String objectStr = new String(Base64.encode(baos.toByteArray(), Base64.DEFAULT));
        baos.close();
        oos.close();

        putString(context, key, objectStr);
    }

    /**获取对象*/
    private Object get(Context context, String key)throws IOException, ClassNotFoundException {
        String wordBase64 = getString(context, key);
        // 将base64格式字符串还原成byte数组
        if (TextUtils.isEmpty(wordBase64)) { //不可少，否则在下面会报java.io.StreamCorruptedException
            return null;
        }
        byte[]               objBytes = Base64.decode(wordBase64.getBytes(), Base64.DEFAULT);
        ByteArrayInputStream bais     = new ByteArrayInputStream(objBytes);
        ObjectInputStream ois      = new ObjectInputStream(bais);
        // 将byte数组转换成product对象
        Object obj = ois.readObject();
        bais.close();
        ois.close();
        return obj;
    }

    /**
     * 获取字符串
     *
     * @param context 上下文
     * @param key     字符串的键
     * @return 得到的字符串
     */
    public String getString(Context context, String key) {
        return sp.getString(key, "");
    }

    /**
     * 存入字符串
     *
     * @param context 上下文
     * @param key     字符串的键
     * @param value   字符串的值
     */
    public void putString(Context context, String key, String value) {
        //SharedPreferences preferences = getSp(context);
        //存入数据
        editor = sp.edit();
        editor.putString(key, value);
        editor.commit();
    }
    /**
     * 获取字符串
     *
     * @param context 上下文
     * @param key     字符串的键
     * @param value   字符串的默认值
     * @return 得到的字符串
     */
    public String getString(Context context, String key, String value) {
        return sp.getString(key, value);
    }

    /**
     * 存储List集合
     * @param context 上下文
     * @param key 存储的键
     * @param list 存储的集合
     */
    public  void putList(Context context, String key, List<? extends Serializable> list) {
        try {
            put(context, key, list);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取List集合
     * @param context 上下文
     * @param key 键
     * @param <E> 指定泛型
     * @return List集合
     */
    public  <E extends Serializable> List<E> getList(Context context, String key) {
        try {
            return (List<E>) get(context, key);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 是否是第一次打开收货地址定位
     * @return
     */
    public String getExpiredTime(){
        return sp.getString("expiredTime","");
    }

    public void setExpiredTime(String expiredTime){
        editor.putString("expiredTime",expiredTime);
        editor.commit();
    }



}
